package com.pwrd.sframe.core;

import com.pwrd.sframe.core.thread.ThreadHandler;
import com.pwrd.sframe.core.thread.RunnableCase;
import com.pwrd.sframe.support.log.Log;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther syc.
 * @Date 2017/1/22 15:04.
 */
public class Node implements RunnableCase{

    private String key;

    public static final Map<String, Port> ports = new ConcurrentHashMap<>();

    private ThreadHandler thread;
    //是否已开启
    private volatile boolean start;

    public Node(String key) {

        this.key = key;
        thread = new ThreadHandler(this, key);
    }

    public void addPort(String key, Port port) {
        ports.put(key, port);
    }

    public void startup() {
        start = true;
        thread.startup();
    }

    @Override
    public void run() {
        pulse();
    }

    private void pulse() {
        // 处理其他node发送的请求
    }

    public String getKey() {
        return key;
    }

    public Port getPort(String key) {
        return ports.get(key);
    }

    public boolean isSameNode(String toNodeKey) {
        boolean isSameNode = false;
        if(key.equals(toNodeKey)) {
            isSameNode = true;
        }
        return isSameNode;
    }

    /**
     * 处理接收到的Call调用
     * @param call
     */
    public void callHandle(Call call) {
        Port toPort = ports.get(call.toPoint.portKey);
        if (toPort != null) {
            toPort.addCall(call);
        } else {
            if(Log.rpc.isInfoEnabled()) {
                Log.rpc.info("Receiver port={} is not exist in node={} ：call={}",
                        call.toPoint.portKey, call.toPoint.nodeKey, call);
            }
        }
    }
}
